import 'package:flutter/material.dart';

class LeafRenderWidgetPage extends StatefulWidget {
  const LeafRenderWidgetPage({super.key});

  @override
  State<LeafRenderWidgetPage> createState() => _LeafRenderWidgetPageState();
}

class _LeafRenderWidgetPageState extends State<LeafRenderWidgetPage>
    with SingleTickerProviderStateMixin {
  late Animation<double> _sizeAnimation;
  late AnimationController _controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 创建动画控制器（2秒循环动画）
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true); // 循环播放（变大后变小）
    // 大小动画：0.1 -> 1.0
    _sizeAnimation = Tween<double>(begin: 0.1, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    )..addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("自定义Leaf widget")),
      body: CircleWidget(_sizeAnimation.value),
    );
  }
}

class CircleWidget extends LeafRenderObjectWidget {
  final double sizeFactor;

  CircleWidget(this.sizeFactor);

  @override
  RenderObject createRenderObject(BuildContext context) {
    return CircleRender(sizeFactor);
  }

  @override
  void updateRenderObject(
    BuildContext context,
    covariant CircleRender renderObject,
  ) {
    renderObject.sizeFactor = sizeFactor;
  }
}

class CircleRender extends RenderBox {
  double _sizeFactor;

  CircleRender(this._sizeFactor);

  // 添加 setter 方法 - 关键修复点
  set sizeFactor(double value) {
    if (_sizeFactor == value) return;
    _sizeFactor = value;
    // 标记需要重绘
    markNeedsPaint();
  }

  @override
  void performLayout() {
    size = constraints.constrain(Size(100, 100));
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    super.paint(context, offset);
    context.canvas.drawRect(offset & size, Paint()..color = Colors.red);
    context.canvas.drawCircle(
      size.center(offset),
      (size.width / 2) * _sizeFactor,
      Paint()..color = Colors.black,
    );
  }
}
